package com.sun.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.logging.Logger;

/**
 * 实现Web层的⽇志切⾯
 * https://blog.csdn.net/LuQiaoYa/article/details/88233846?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-1-88233846-blog-80905791.pc_relevant_3mothn_strategy_recovery&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-1-88233846-blog-80905791.pc_relevant_3mothn_strategy_recovery&utm_relevant_index=2
 * @author Administrator
 */
@Order(5)
@Aspect
@Component
public class WebLogAspect {
    private Logger logger = Logger.getLogger(String.valueOf(getClass()));

    ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Pointcut("execution(public * com.sun.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint)throws Throwable{
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //记录下请求内容
        logger.info("URL: "+request.getRequestURL().toString());
        logger.info("HTTP_METHOD: "+request.getMethod());
        logger.info("IP: "+ request.getRemoteAddr());
        logger.info("CLASS_METHOD: "+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        logger.info("ARGS: "+ Arrays.toString(joinPoint.getArgs()));
        System.out.println("1111111111111111111");
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
        logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
        System.out.println("2222222222222222222222222");
    }
}
